// 直线责任部门分析
<template>
  <a-row :gutter="24" class="search-row">
    <x-card>
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="12">
            <a-col :span="6">
              <a-form-item label="隐患单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-tree-select
                  allowClear
                  showSearch
                  style="scroll:true"
                  tree-node-filter-prop="title"
                  v-model="queryParam.OrganizationName"
                  :treeData="QHSEOrganizationTree"
                  v-if="QHSEOrganizationTree.length"
                  @change="handleOrganizationSelectChange"
                  :defaultExpandAll="true"
                  :defaultExpandedKeys="defaultExpandedKeys"
                  :replaceFields="replaceFields"
                  ref="tree"
                  placeholder="请选择隐患单位"
                  :title="queryParam.OrganizationName" />
              </a-form-item>
            </a-col>
            <a-col :span="7">
              <a-form-item label="检查时间" :labelCol="{ style: 'width:115px' }" :wrapperCol="wrapperCol">
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange1"
                  :style="{ width: '50%' }"
                  v-model="TimeOn1" />
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange2"
                  :style="{ width: '50%' }"
                  v-model="TimeEnd1" />
              </a-form-item>
            </a-col>
            <a-col :span="7">
              <a-form-item label="对比时间" :labelCol="{ style: 'width:115px' }" :wrapperCol="wrapperCol">
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange3"
                  :style="{ width: '50%' }"
                  v-model="TimeOn2" />
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  @change="onChange4"
                  :style="{ width: '50%' }"
                  v-model="TimeEnd2" />
              </a-form-item>
            </a-col>
            <a-col :span="3" style="margin-bottom: 3px;">
              <a-button type="primary" @click="handleClick" :loading="saving">查询</a-button>
              <a-button type="default" @click="exportToExcel" style="margin-left: 8px;">导出</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-row :gutter="48" class="search-row">
      <a-col :span="24">
        <a-divider orientation="left" style="font-weight: bold; margin-top: -1px;"> 隐患直线责任部门分析</a-divider>
        <a-card style="overflow-y: auto; margin-top: -8px;" :bordered="false">
          <a-row style="width: 100%; height: 500px; margin-top: 20px">
            <a-col :span="24">
              <a-progress
                v-if="batchExportLoading1"
                :percent="exportProgress1"
                status="active"
              />
              <div id="bar-chart-container1" style="width: 100%; height: 500px;"></div>
            </a-col>
            <a-col :span="24">
              <a-progress
                v-if="batchExportLoading2"
                :percent="exportProgress2"
                status="active"
              />
              <div id="bar-chart-container2" style="width: 100%; height: 500px;"></div>
            </a-col>
          </a-row>
          <a-row style="width: 100%; height: 400px;">
            <a-col :span="24">
              <a-progress
                v-if="batchExportLoading"
                :percent="exportProgress"
                status="active"
              />
              <a-table
                bordered
                :columns="columns"
                :dataSource="loadData"
                :alert="false"
                :pagination="false"
                :rowKey="(record, index) => index"
              >
              </a-table>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </a-row>
</template>

<script>
import { STable, XCard, XDown } from '@/components'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import moment from 'moment'
import {
  getQHSEStartCompareSelfDangerDepartmentCheckCount,
  getQHSEGetCompareSelfDangerDepartmentCheckCountStatus,
  getQHSETakeCompareSelfDangerDepartmentCheckCount,
  getQHSEStartCompareSuperviseDangerDepartmentCheckCount,
  getQHSEGetCompareSuperviseDangerDepartmentCheckCountStatus,
  getQHSETakeCompareSuperviseDangerDepartmentCheckCount,
  getQHSEStartTableTableDangerDirectDepartmentCheckCount,
  getQHSEGetTableDangerDirectDepartmentCheckCountStatus,
  getQHSETakeTableDangerDirectDepartmentCheckCount
} from '@/api/modular/system/QHSEDANReports/QHSEDirMents'
import { mapGetters } from 'vuex'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'

export default {
  components: {
    XDown,
    XCard,
    STable
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      defaultExpandedKeys: [],
      QHSEOrganizationTree: [],
      secondOraName: {
        id: ''
      },
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      queryParam: {
        TimeOn1: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd1: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
        TimeOn2: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd2: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
        OrganizationName: '川庆钻探',
        OrganizationId: '00'
      },
      TimeEnd1: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn1: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      TimeEnd2: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      TimeOn2: moment(new Date(), 'YYYY-MM-DD').subtract(2, 'months'),
      saving: false,
      // 表头
      columns: [
        {
          title: '隐患直线责任部门',
          dataIndex: 'compareType'
        },
        {
          title: '',
          children: [
            {
              title: '自检自查数',
              dataIndex: 'selfValue1'
            }
          ]
        },
        {
          title: '',
          children: [
            {
              title: '自检自查数',
              dataIndex: 'selfValue2'
            }
          ]
        },
        {
          title: '',
          children: [
            {
              title: '监督查纠数',
              dataIndex: 'superviseValue1'
            }
          ]
        },
        {
          title: '',
          children: [
            {
              title: '监督查纠数',
              dataIndex: 'superviseValue2'
            }
          ]
        }
      ],
      loadData: [],
      dangerCheckData: [],
      task: {
        Id: ''
      },
      task1: {
        Id: ''
      },
      task2: {
        Id: ''
      },
      exportProgress: 0,
      exportProgress1: 0,
      exportProgress2: 0,
      status: '',
      status1: '',
      status2: '',
      batchExportLoading: false,
      batchExportLoading1: false,
      batchExportLoading2: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getQHSEOrganizationTree()
  },
  methods: {
    // 更改隐患单位
    handleOrganizationSelectChange(val, opt, extra) {
      if (extra.triggerNode === undefined) {
        this.queryParam.OrganizationName = null
        this.queryParam.OrganizationId = null
      } else {
        const option = extra.triggerNode._props.title
        this.queryParam.OrganizationName = option
        this.queryParam.OrganizationId = extra.triggerNode._props.value
      }
    },
    // 组织树
    getQHSEOrganizationTree() {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
      })
    },
    exportToExcel() {
      // 设置导出的数据，手动调整字段名称
      const exportData = this.loadData.map((item, index) => ({
        隐患级别: item.compareType,
        检查时间自检自查数: item.selfValue1,
        自检自查数: item.selfValue2,
        检查时间监督查纠数: item.superviseValue1,
        对比时间监督查纠数: item.superviseValue2
      }))
      // 创建工作表和工作簿
      const ws = XLSX.utils.json_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '隐患专业类别分析')
      // 导出 Excel 文件，文件名带当前日期
      XLSX.writeFile(wb, `隐患专业类别分析_${moment().format('YYYYMMDD')}.xlsx`)
    },
    handleClick() {
      if ((!this.TimeOn1 && !this.TimeEnd1) || (this.TimeOn1 && this.TimeEnd1) && (!this.TimeOn2 && !this.TimeEnd2) || (this.TimeOn2 && this.TimeEnd2)) {
        this.columns[1].title = `${this.TimeOn1.format('YYYY-MM-DD')} - ${this.TimeEnd1.format('YYYY-MM-DD')}`
        this.columns[2].title = `${this.TimeOn2.format('YYYY-MM-DD')} - ${this.TimeEnd2.format('YYYY-MM-DD')}`
        this.columns[3].title = `${this.TimeOn1.format('YYYY-MM-DD')} - ${this.TimeEnd1.format('YYYY-MM-DD')}`
        this.columns[4].title = `${this.TimeOn2.format('YYYY-MM-DD')} - ${this.TimeEnd2.format('YYYY-MM-DD')}`
        // 后端方法
        this.select()
        this.loadTableData()
        this.loadTableData1()
      } else {
        this.$message.warning('请填写完整的查询条件')
      }
    },
    select() {
      // 后端方法
      this.saving = true
      this.batchExportLoading = true
      getQHSEStartTableTableDangerDirectDepartmentCheckCount(this.queryParam).then((res) => {
        this.task.Id = res.taskId
      })
      this.exportProgress = 0
      // 定时器和轮询是并发的，不是异步的
      setInterval(() => {
        if (this.exportProgress < 90) {
          this.exportProgress += 5
        }
      }, 500)
      // 每 5 秒轮询状态
      const statusInterval = setInterval(() => {
        getQHSEGetTableDangerDirectDepartmentCheckCountStatus(this.task).then((res) => {
          this.status = res.status
          if (this.status === 'completed') {
            // 清除进度定时器，确保定时器被清除
            clearInterval(statusInterval)
            getQHSETakeTableDangerDirectDepartmentCheckCount(this.task).then((res) => {
              this.loadData = res.data.table
              this.exportProgress += 10
              this.batchExportLoading = false
            })
            .finally(() => {
              // 不管成功失败都要取消loading状态
              this.saving = false
            })
          }
        }).catch(error => {
            console.error('状态获取失败:', error)
            clearInterval(statusInterval) // 出现错误时，也要清除定时器
            this.$message.error('获取数据失败')
        })
      }, 5000)
    },
    loadTableData() {
      this.batchExportLoading1 = true
      getQHSEStartCompareSelfDangerDepartmentCheckCount(this.queryParam).then(res => {
        this.task1.Id = res.taskId
      })
      this.exportProgress1 = 0
      setInterval(() => {
        if (this.exportProgress1 < 90) {
          this.exportProgress1 += 10
        }
      }, 500)
      const statusInterval = setInterval(() => {
        getQHSEGetCompareSelfDangerDepartmentCheckCountStatus(this.task1).then(res => {
          this.status1 = res.status
          if (this.status1 === 'completed') {
            // 清除进度定时器，确保定时器被清除
            clearInterval(statusInterval)
            getQHSETakeCompareSelfDangerDepartmentCheckCount(this.task1).then((res) => {
              this.renderMulBarChart(res.data.compare, 'bar-chart-container1', 'vertical')
              this.exportProgress += 10
              this.batchExportLoading1 = false
            })
            .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
            })
          }
        }).catch(error => {
          console.error('状态获取失败:', error)
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          this.$message.error('获取数据失败！')
        })
      }, 5000)
    },
    loadTableData1() {
      this.batchExportLoading2 = true
      getQHSEStartCompareSuperviseDangerDepartmentCheckCount(this.queryParam).then(res => {
        this.task2.Id = res.taskId
      })
      this.exportProgress2 = 0
      setInterval(() => {
        if (this.exportProgress2 < 90) {
          this.exportProgress2 += 10
        }
      }, 500)
      const statusInterval = setInterval(() => {
        getQHSEGetCompareSuperviseDangerDepartmentCheckCountStatus(this.task2).then(res => {
          this.status2 = res.status
          if (this.status2 === 'completed') {
            // 清除进度定时器，确保定时器被清除
            clearInterval(statusInterval)
            getQHSETakeCompareSuperviseDangerDepartmentCheckCount(this.task2).then((res) => {
              this.renderMulBarChart(res.data.compare, 'bar-chart-container2', 'vertical')
              this.exportProgress2 += 10
              this.batchExportLoading2 = false
            })
            .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
            })
          }
        }).catch(error => {
          console.error('状态获取失败:', error)
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          this.$message.error('获取数据失败！')
        })
      }, 5000)
    },
    renderMulBarChart(data, containerId, chartType) {
      const barChartContainer = document.getElementById(containerId)
      const barChart = echarts.init(barChartContainer)
      if (data.item === undefined) {
        return
      }
      const barChartData = data.item
      const barChartOption = {
        // 默认标题
        title: {
          text: '',
          textStyle: {
            fontWeight: 'bold',
            fontSize: 20
          },
          left: 'center' // 标题水平居中
        },
        // 提示框配置 指针悬停在数据上时，显示数据提示
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        // 图例设置 水平 居中 固定底部
        legend: {
          orient: 'horizontal',
          x: 'center',
          y: 'bottom',
          textStyle: {
            fontSize: 16
          }
        },
        // 网格配置
        grid: {
          containLabel: true,
          top: 60
        },
        // X轴为类别型
        xAxis: {
          type: 'category'
        },
        // Y轴为数值型
        yAxis: {
          type: 'value'
        },
        // 每个对象代表一个系列，柱状图中的一个柱子合集
        series: []
      }
      const headerRow = barChartData[0]
      // console.log('headerRow:', headerRow)
      for (var i = 1; i < headerRow.length; i++) {
        var dataObj = {
          // 数据点的名称，即哪年哪月
          name: headerRow[i],
          // 柱状图
          type: 'bar',
          // 去除第一行，按列提取X轴标签对应的数值
          data: barChartData.slice(1).map(row => row[i]),
          label: {
              // 在柱子上显示数值标签
              show: true,
              // 数值标签的位置在顶部
              position: 'top'
              // formatter: function (params) {
              //   // 根据seriesIndex来决定是否显示标签
              //   if (params.seriesIndex % 1 === 0) {
              //     return params.value
              //   } else {
              //     return ''
              //   }
              // }
            }
        }
        barChartOption.series.push(dataObj)
      }
      // console.log('data:', barChartData.slice(1).map(row => row[i]))
      barChartOption.title.text = barChartData[0][0]
      // 超过13个专业竖着显示横坐标
      if (barChartData.length > 13) {
          barChartOption.xAxis.axisLabel = {
            formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            },
            fontSize: 14
        }
      } else {
        barChartOption.xAxis.axisLabel = {
          interval: 0,
          formatter: null,
          fontSize: 14 // 设置较大的字体大小
        }
      }
      // 设置X轴的标签名称
      barChartOption.xAxis.data = barChartData.slice(1).map(row => row[0])
      // if (barChartData.length > 0) {
      //   barChart.setOption(barChartOption)
      // }
      barChart.setOption(barChartOption)
    },
    onChange1(date, dateString) {
      // console.log(dateString, date)
      if (this.queryParam.TimeEnd1 && dateString) {
        if (dateString > this.queryParam.TimeEnd1) {
          this.$message.error('检查开始时间不能晚于结束时间')
          this.TimeEnd1 = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn1 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn1 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd1 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeOn1 = dateString
        }
      } else {
        this.queryParam.TimeOn1 = dateString
      }
      // console.log('TimeOn1', this.queryParam.TimeOn1)
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn1 && dateString) {
        if (this.queryParam.TimeOn1 > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd1 = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn1 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn1 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd1 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd1 = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd1 = dateString + 'T' + moment().format('23:59:59')
      }
      // console.log('TimeEnd1', this.queryParam.TimeEnd1)
    },
    onChange3(date, dateString) {
      // console.log(dateString, date)
      if (this.queryParam.TimeEnd2 && dateString) {
        if (dateString > this.queryParam.TimeEnd2) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd2 = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn2 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn2 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd2 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeOn2 = dateString
        }
      } else {
        this.queryParam.TimeOn2 = dateString
      }
      // console.log('TimeOn2', this.queryParam.TimeOn2)
    },
    onChange4(date, dateString) {
      if (this.queryParam.TimeOn2 && dateString) {
        if (this.queryParam.TimeOn2 > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd2 = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn2 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn2 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd2 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd2 = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd2 = dateString + 'T' + moment().format('23:59:59')
      }
      // console.log('TimeEnd2 ', this.queryParam.TimeEnd2)
    }
  }
}

</script>

<style scoped="less"></style>
